package com.projx.accounting.controller;

import com.projx.accounting.module.Bill;
import com.projx.accounting.service.AuthService;
import com.projx.accounting.service.BillService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/api/bills")
public class BillController {
    private final BillService svc;
    private final AuthService auth;

    public BillController(BillService svc, AuthService auth) {
        this.svc = svc;
        this.auth = auth;
    }

    @PostMapping
    public ResponseEntity<Bill> create(@RequestHeader("X-Auth-Token") String token, @RequestBody Bill bill) {
        String ownerId = auth.getUserIdForToken(token).orElse(null);
        if (ownerId == null) return ResponseEntity.status(401).build();
        bill.setOwnerId(ownerId);
        Bill created = svc.create(bill);
        return ResponseEntity.created(URI.create("/api/bills/" + created.getId())).body(created);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Bill> get(@RequestHeader("X-Auth-Token") String token, @PathVariable String id) {
        String ownerId = auth.getUserIdForToken(token).orElse(null);
        if (ownerId == null) return ResponseEntity.status(401).build();
        return svc.findById(id)
                .filter(b -> ownerId.equals(b.getOwnerId()))
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping
    public List<Bill> list(@RequestHeader("X-Auth-Token") String token) {
        String ownerId = auth.getUserIdForToken(token).orElse(null);
        if (ownerId == null) return List.of();
        return svc.listByOwner(ownerId);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Bill> update(@RequestHeader("X-Auth-Token") String token, @PathVariable String id, @RequestBody Bill bill) {
        String ownerId = auth.getUserIdForToken(token).orElse(null);
        if (ownerId == null) return ResponseEntity.status(401).build();
        if (bill.getId() == null) bill.setId(id);
        if (!id.equals(bill.getId())) return ResponseEntity.badRequest().build();
        // ensure owner unchanged
        bill.setOwnerId(ownerId);
        Bill updated = svc.update(bill);
        return ResponseEntity.ok(updated);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@RequestHeader("X-Auth-Token") String token, @PathVariable String id) {
        String ownerId = auth.getUserIdForToken(token).orElse(null);
        if (ownerId == null) return ResponseEntity.status(401).build();
        var opt = svc.findById(id).filter(b -> ownerId.equals(b.getOwnerId()));
        if (opt.isEmpty()) return ResponseEntity.notFound().build();
        boolean removed = svc.delete(id);
        return removed ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
    }

    @GetMapping("/summary")
    public ResponseEntity<Double> summary(@RequestHeader("X-Auth-Token") String token,
                                          @RequestParam(required = false) String from,
                                          @RequestParam(required = false) String to) {
        String ownerId = auth.getUserIdForToken(token).orElse(null);
        if (ownerId == null) return ResponseEntity.status(401).build();
        java.time.OffsetDateTime f = from == null ? null : java.time.OffsetDateTime.parse(from);
        java.time.OffsetDateTime t = to == null ? null : java.time.OffsetDateTime.parse(to);
        double sum = svc.sumByOwnerBetween(ownerId, f, t);
        return ResponseEntity.ok(sum);
    }
}
